package classes;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import containers.KeywordContainer;
import containers.Page;
import containers.StatisticsContainer;

public class PageAnalyzer {
	private int myPageCount; //counter for pages analyzed
	private int myTotalWords; //counter for word count
	private long  myTotalRunningTime; //count running time for all analyzations
	//following two are parallel array for keywords and count per keyword
	private String[] myKeywords; //holds all keywords
	private int[] myKeywordTally; //counts keyword count for each keyword
	private int numKeywords; //the number of keywords inputted by user (max = 10)
	private int myTotalLinks; //to calc avg urls per page
	
	private Map<String, Integer> uniqueWords;
	
	public PageAnalyzer(List<String> keywords) {
		myKeywords = keywords.toArray(new String[keywords.size()]);
		myKeywordTally = new int[keywords.size()];
		uniqueWords = new TreeMap<String, Integer>();
		numKeywords = keywords.size();
	}
	
	/**
	 * Analyzes page and tabulates statistics.
	 * @param thePage	The page to analyze.
	 */
	public void analyzePage(final Page thePage) {
		List<String> theWords = thePage.getWords();
		
		//for each word in the page, check against the keywords
		//count word and update specific keyword count
		for (String word : theWords) {
			myTotalWords++;
			for (int i = 0; i < numKeywords; i++) {
				if (word.equalsIgnoreCase(myKeywords[i])) {
					myKeywordTally[i]++;
				}
			}
			//test for words in test site
			if (uniqueWords.get(word.toLowerCase()) == null) {
				uniqueWords.put(word.toLowerCase(), 1);
			} else {
				uniqueWords.put(word.toLowerCase(), uniqueWords.get(word.toLowerCase()).intValue()+1);
			}
		}

		myTotalRunningTime += thePage.getParseTime();

		myPageCount++;
		myTotalLinks+=thePage.getNumLinks();
				
//		System.out.println("analization complete. Pages counted: " + myPageCount + ", total words: " + myTotalWords + ", total links: " + myTotalLinks + ", links this page: " + thePage.getNumLinks());
	}
	
	public StatisticsContainer tabulateStatistics() {
		//output all words and instance count
		for (Iterator i = uniqueWords.keySet().iterator(); i.hasNext(); ) {
			Object key = i.next();
		}
		
		List<KeywordContainer> kst = new ArrayList<KeywordContainer>();
		for (int i = 0; i < numKeywords; i++) {
			KeywordContainer kw = new KeywordContainer(myKeywords[i], myKeywordTally[i], myKeywordTally[i]/(double)myPageCount);
			kst.add(kw);
		}
		StatisticsContainer stats = new StatisticsContainer(myPageCount, myTotalWords/myPageCount, myTotalLinks/myPageCount, kst, myTotalRunningTime/myPageCount, myTotalRunningTime);
		return stats;
	}
	
	
	
}
